from rest_framework import generics
from rest_framework.views import status

from rest_framework.response import Response

import copy



class Custcom_Generics_List_View(generics.ListCreateAPIView):


    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            res = self.get_paginated_response(serializer.data)
            return self.format_respon_data(res)

        serializer = self.get_serializer(queryset, many=True)
        return self.format_respon_data(Response(serializer.data))

    def format_respon_data(self, res):
        """
         格式化返回数据
        :param res: django Response 对象
        :return: django Response 对象
        """

        return res

    def create(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        message = {"code": 20000, "message": "success", "data": serializer.data}
        return Response(message, status=status.HTTP_201_CREATED, headers=headers)


class Custcom_Generics_Detail_View(generics.RetrieveUpdateDestroyAPIView):

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return self.format_respon_data(Response(serializer.data))

    def format_respon_data(self, res):
        """
         格式化返回数据
        :param res: django Response 对象
        :return: django Response 对象
        """
        if isinstance(res, Response):
            data = copy.deepcopy(res.data)
            res.data = {"code": 20000, "message": "success", "data": data}
        return res

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        message = {"code": 20000, "message": "success", "data": serializer.data}
        return Response(message)
